// pages/car/car.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    address:'',
    car:'',
    checkedAll:'',
    allPrice:0,
    allNum:0
  },
  handleChooseAddress(){
    wx.chooseAddress(
      {
        success:data=>{
          wx.setStorageSync("address", data)
        }
      }
    )
  },
  updateChk(e){
    const{id} = e.currentTarget.dataset
    const{car} = this.data
    var index = this.data.car.findIndex(v=>v.goods_id===id)
    car[index].checked =!car[index].checked
    this.setData({car})
    wx.setStorageSync("car",car)
    var checkedAll = car.every(v => v.checked === true)
    this.setData({ checkedAll })
    let allPrice=0,allNum=0
    car.forEach(
      v => {
        if (v.checked) {
          allPrice += v.goods_price * v.num
          allNum += v.num
          this.setData({ allPrice, allNum })
          console.log(allPrice, allNum)
        }else{
          
        }
      }
    )
   this.setData({allPrice,allNum})
   
    console.log(car)
    
  },
  updateChkA(){
      let {car,checkedAll} = this.data
      checkedAll=!checkedAll
      car.forEach(v=>{v.checked=checkedAll})
    wx.setStorageSync("car", car)
    this.setData({car,checkedAll})
    console.log(this.data.car)
    let allPrice = 0, allNum = 0
    car.forEach(
      v => {
        if (v.checked) {
          allPrice += v.goods_price * v.num
          allNum += v.num
          this.setData({ allPrice, allNum })
          console.log(allPrice, allNum)
        } else {

        }
      }
    )
    this.setData({allPrice,allNum})
  },
  handleUpdateNum(e){
    let{id,operation} = e.currentTarget.dataset
    let{car} = this.data
    var index = car.findIndex(v=>v.goods_id===id)
  car[index].num+=operation
  this.setData({car})
  console.log(car,id,operation)
  wx.setStorageSync("car",car)
    let allPrice = 0, allNum = 0
    car.forEach(
      v => {
        if (v.checked) {
          allPrice += v.goods_price * v.num
          allNum += v.num
          this.setData({ allPrice, allNum })
          console.log(allPrice, allNum)
        } else {

        }
      }
    )
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var address = wx.getStorageSync("address")
    this.setData({
      address:address
    })
    var car = wx.getStorageSync("car")
      console.log(car)
      this.setData({ car: car })
      var checkedAll = car.every(v => v.checked === true)
      this.setData({ checkedAll })
      console.log(this.data.checkedAll)
      let allPrice=0,allNum=0
      car.forEach(
        v=>{
          if(v.checked){
            allPrice += v.goods_price*v.num
            allNum +=v.num
            this.setData({allPrice,allNum})
          }
        }
      )
    },
  

  })